package com.elh.linkedlist;

/**
 * @author liulei
 **/
public class SingleLinkedList {

    private int size;

    private Node head;

    /**
     * 在头部中插入节点
     *
     * @param data
     */
    public void addHead(Object data) {
        Node newNode = new Node();
        newNode.setData(data);
        newNode.setNext(head);
        head = newNode;
        size++;
    }

    /**
     * 在尾部插入节点
     *
     * @param data
     */
    public void push(Object data) {
        Node newNode = new Node();
        newNode.setData(data);
        if (head == null) {
            head = newNode;
        } else {
            Node temp = head;
            // 找到最后一个节点
            while ((temp.getNext()) != null) {
                temp = temp.getNext();
            }
            temp.setNext(newNode);
        }
        size++;
    }


    /**
     * 在指定节点插入节点
     *
     * @param prevNode
     * @param newData
     */
    public void insertAfter(Node prevNode, Object newData) {
        Node newNode = new Node();
        newNode.setData(newData);
        Node prevNodeNext = prevNode.getNext();
        prevNode.setNext(newNode);
        newNode.setNext(prevNodeNext);
        size++;
    }


    public boolean isEmpty() {
        return (size == 0);
    }

    /**
     * 删除一个节点
     *
     * @param value
     * @return
     */
    public boolean delete(Object value) {
        Node temp = head;
        Node pre = head;
        while (!temp.getData().equals(value)) {
            if (temp.getNext() == null) {
                return false;
            } else {
                pre = temp;
                temp = temp.getNext();
            }
        }
        // 头节点
        if (temp == head) {
            head = temp.getNext();
        } else {
            // 非头节点
            pre.setNext(temp.getNext());
        }
        size--;
        return true;
    }

    /**
     * 打印链表
     */
    public void printList() {
        Node tnode = head;
        while (tnode != null) {
            System.out.print(tnode.getData() + " ");
            tnode = tnode.getNext();
        }
    }


}
